// pages/dynamic/dynamic.js
var app = getApp();
var weChat = wx.getStorageSync('weChatInfo');
var address = app.globalData.address;
var util = require('../../utils/util.js');
var that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    weChatInfo: app.globalData.weChatInfo,
    hadFont:false,//是否展开文字输入
    focus:false,//输入框是否有焦点
    currentPage:1,//分页
    phone:null,
    list:[],
    val:'',
    font:'我要表达什么意思呢?我要表达什么意思呢，我要表达什么意思呢，我要表达什么意思呢，我要表达什么意思呢，我要表达什么意思呢，我要表达什么意思呢，我要表达什么意思呢，我要表达什么意思呢？',
    
  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    //获得dialog组件
    this.dialog = this.selectComponent("#dialog");
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;

    that.getSystem();
    app.getUserInfo(function (r) {
      // that.showList();
    })
  },

  onShow: function () {
    that = this;
    if (wx.getStorageSync('check') || wx.getStorageSync('count1') == 0) {
      if (that.data.list.length > 0) {
        that.setData({
          list: [],
          currentPage: 1
        })
        wx.setStorageSync('count1', 1);
        wx.setStorageSync('check', false);
        that.showList();
      } else {
        that.setData({
          list: [],
          currentPage: 1,
        })
        wx.setStorageSync('count1', 1);
        wx.setStorageSync('check', false);
        that.showList();
      }
    }
  },
  getSystem:function(){
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    })
  },
  // 网页加载即显示动态信息
  showList:function(e){
    let url = address + 'Dynamic/toDynamic';
    let params = {
      'companyId': wx.getStorageSync('companyId'),
      'businessId': wx.getStorageSync('id'),
      'currentPage': that.data.currentPage
    };
    let session = app.globalData.sessionId;
    util.headLoading(url, params, '正在加载中', session,function(res){
      if (res.myList){
        var list = res.myList;
         console.log(list)
        that.setData({
          totalPageCount: res.totalPageCount
        })
        // 时间的转换
        let nowTime = new Date().getTime();
        list.forEach(function (v, i) {
          // console.log(v.dynamicContentv.dynamicContent.length)
          v.comThat = false;
          let creatTime = new Date(v.sendDate).getTime();
          let timeing = parseInt((nowTime - creatTime) / 60000);
          if (timeing <= 1) {
            v.sendDate = '刚刚';
          } else if (timeing > 1 && timeing <= 60) {
            v.sendDate = timeing + '分钟前';
          } else if (timeing > 60) {
            let hours = parseInt(timeing / 60);
            if (hours >= 1 && hours <= 24) {
              v.sendDate = hours + '小时前';
            } else if (hours > 24) {
              let days = parseInt(hours / 24);
              if (days >= 1 && days <= 30) {
                v.sendDate = days + '天前';
              }
            }
          }
        })
        that.setData({
          list: that.data.list.concat(list),
          length: list.length
        })
      }else{
        wx.showToast({
          title: '暂无动态',
          icon: 'none',
          duration: 3000000
        })
      }
    },function(){
      
    });

  },
  // 点击全文或者收起文字
  clickFont:function(e){
    let index = e.currentTarget.dataset.index;
    let list = that.data.list;
    list.forEach(function (v, i) {
      if(i != index){
        if (v.hadFont)//只操作除自己之外为true的
          v.hadFont = false;
      }     
    })//此处一定要加此逻辑，是为了控制已经展开的全文可以缩回去
    list[index].hadFont = !list[index].hadFont;   
    that.setData({
      list: list
    })
  },

  // 点击图片查看大图
  toPre:function(e){
    var url = e.currentTarget.dataset.url;
    var index = e.currentTarget.dataset.index;
    var idx = e.currentTarget.dataset.idx;
    var urls = [];
    that.data.list[index].dynamicContentv.dynamicImg.forEach(function(v,i){      
      urls.push(v.imgUrl)
    })
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  // 点击纯文字跳转
  toTitle:function(e){
    let list = e.currentTarget.dataset.list;
    wx.setStorageSync('list', list);
    
    wx.navigateTo({
      url: "subPackages/title/title",
    })
  },
  // 点击文章跳转
  toTitle2:function(e){
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/dynamic/subPackages/title-view/title-view?url='+url,
    })
  },
  // 点击信息图展开点赞或评论
  toComThat:function(e){
    let index = e.currentTarget.dataset.index;
    let list = that.data.list;
    list.forEach(function (v, i) {
      if (i != index) {
        if (v.comThat) {
          v.comThat = false;
        }
      } else {
        v.comThat = !v.comThat;
      }
    })
    that.setData({
      list: list
    })
  },
  

  // 是否点赞
  toIsZan:function(e){
    let index = e.currentTarget.dataset.index;
    let list = that.data.list;

    wx.request({
      url: address + 'Dynamic/likePraise',
      data:{
        dynamicId: list[index].id
      },
      header: {
        'content-type': 'application/json', 'Cookie': 'JSESSIONID=' + app.globalData.sessionId
      },
      success:function(result){
        if(result.data == 1){
          let zanList;
          if (list[index].praiseNameAll.name) {
            zanList = list[index].praiseNameAll.name;
          } else {
            list[index].praiseNameAll.name = '';
            zanList = list[index].praiseNameAll.name;
          }
          if (list[index].isPraise == 0) {
            list[index].isPraise = 1;
            if (zanList.length > 0) {
              zanList += ',' + app.globalData.weChatInfo.nickName;
              list[index].praiseNameAll.name = zanList;
            } else {
              zanList += app.globalData.weChatInfo.nickName;
              list[index].praiseNameAll.name = zanList;
            }
          } else if (list[index].isPraise == 1) {
            list[index].isPraise = 0;
            let arr = zanList.split(',');
            let idx;
            arr.forEach(function (v, i) {
              if (v == app.globalData.weChatInfo.nickName) {
                idx = i;
              }
            })
            arr.splice(idx, 1);
            let xx = arr.join(',');
            list[index].praiseNameAll.name = xx;
          }
          that.setData({
            list: list
          })
          setTimeout(function () {
            list[index].comThat = false;
            that.setData({
              list: list
            })
          }, 500)
        }
      }
    })

  },
  //监听输入框的变化
  changeInput: function (e) {
    var val = e.detail.value;
    that.setData({
      val: val
    })
  },
  // 点击评论
  toIsMessage:function(e){//缺少接口
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let list = that.data.list;
    list[index].comThat = false;
    that.setData({
      val:'',
      messageIndex:index,
      hadFont:true,
      focus:true,
      comThat:false,
    })
    setTimeout(function(){
      that.setData({
        list: list
      })
    },500)
  },

  // 点击发送按钮评论
  sendMessage:function(e){
    let index = that.data.messageIndex;
    let list = that.data.list;
    wx.request({
      url: address + 'Dynamic/addComment',
      data:{
        dynamicId:list[index].id,
        commentContent:that.data.val
      },
      method:'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'JSESSIONID=' + app.globalData.sessionId
      },
      success:function(result){
        if(result.data == 1){
          console.log('评论成功！')
        }
      }
    })
    let dynamicComments = list[index].dynamicComments;
    if(that.data.val != '' && that.data.val != null){
      let message = {};
      message.commentName = app.globalData.weChatInfo.nickName;
      message.content = that.data.val;
      dynamicComments.push(message);
      that.setData({
        list:list,
        hadFont:false
      })
    }else{
      wx.showToast({
        title: '内容不能为空',
        icon:'none',
        duration:1200
      })
      return;
    }
    
  },
  // testSubmit: function (e) {
  //   util.testSubmit(e);
  // },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;
    that.setData({
      currentPage: 1
    })
    let url = address + 'Dynamic/toDynamic';
    let params = {
      'companyId': wx.getStorageSync('companyId'),
      'businessId': wx.getStorageSync('id'),
      'currentPage': that.data.currentPage
    };
    let session = app.globalData.sessionId;
    util.nomeRequest(url, params, session, function (res) {
      console.log(res)
      if(res.myList){
      var list = res.myList;
      // 时间的转换
      let nowTime = new Date().getTime();
      list.forEach(function (v, i) {
        v.comThat = false;
        let creatTime = new Date(v.sendDate).getTime();
        let timeing = parseInt((nowTime - creatTime) / 60000);

        if (timeing <= 1) {
          v.sendDate = '刚刚';
        } else if (timeing > 1 && timeing <= 60) {
          v.sendDate = timeing + '分钟前';
        } else if (timeing > 60) {
          let hours = parseInt(timeing / 60);
          if (hours >= 1 && hours <= 24) {
            v.sendDate = hours + '小时前';
          } else if (hours > 24) {
            let days = parseInt(hours / 24);
            if (days >= 1 && days <= 30) {
              v.sendDate = days + '天前';
            }
          }
        }
        })
        that.setData({
          list: list
        })
      }
    }, function () {

    });
    setTimeout(function(){
      // 隐藏导航栏加载框
      wx.hideNavigationBarLoading();

      // 停止下拉动作
      wx.stopPullDownRefresh();
    },1000)

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let currentPage = ++that.data.currentPage;
    that.setData({
      currentPage: currentPage
    })
    if (currentPage <= that.data.totalPageCount) {
      wx.showLoading({
        title: '加载中',
      })
      // 请求后台，获取下一页的数据。
      that.showList();
    }else{
      wx.showLoading({
        title: '加载中',
      })
      setTimeout(function(){
        wx.hideLoading();
        wx.showToast({
          title: '没有更多了',
          icon: 'none',
          duration: 1200
        })
      },500)
     
    }
  },

  /**
   * 用户点击右上角分享
   */
  // 点击事件触发page执行转发的函数
  onShareApp: function (e) {
    this.onShareAppMessage();
  },
  // 在page定义转发函数
  onShareAppMessage: function (options) {
    let id = options.target.dataset.id;
    let index = options.target.dataset.index;
    let list = that.data.list;
    console.log(list)
    let name;
    let img;
    if (list[index].type == 2){
      name = list[index].companyName + list[index].screenName;
      img = list[index].headAddress;
    }
    if (list[index].type == 1){
      name = list[index].companyName;
      img = list[index].headPortrait;
    }
    return {
      title: name + '发布的动态',
      imageUrl: img,
      path: 'pages/dynamic/subPackages/message-title/message-title?id=' + id//此处要传入一个名片id去区分是哪个，即重新设定idx的值
    }


  },
  //监听屏幕滚动 判断上下滚动
  onPageScroll: function (ev) {
    let list = that.data.list;
    //当滚动的top值最大或最小时，为什么要做这一步是因为在手机实测小程序的时候会发生滚动条回弹，所以为了处理回弹，设置默认最大最小值
    if (ev.scrollTop <= 0) {
      ev.scrollTop = 0;
    } else if (ev.scrollTop > wx.getSystemInfoSync().windowHeight) {
      ev.scrollTop = wx.getSystemInfoSync().windowHeight;
    }
    //判断浏览器滚动条上下滚动
    if (ev.scrollTop > this.data.scrollTop || ev.scrollTop == wx.getSystemInfoSync().windowHeight) {
      list.forEach(function(v,i){
        if (v.comThat){
          v.comThat = false;
        }
      })
      that.setData({
        hadFont:false,
        list:list
      })
    } else {
      //向上滚动
      list.forEach(function (v, i) {
        if (v.comThat) {
          v.comThat = false;
        }
      })
      that.setData({
        hadFont: false,
        list: list
      })
    }
  },

  // getPhoneNumber: function (e) {
  //   console.log(e)
  //   if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
  //     wx.showModal({
  //       title: '提示',
  //       showCancel: false,
  //       content: '手机号码未授权',
  //       success: function (res) {
  //         wx.navigateTo({
  //           url: '../mall/subPackages/chat/chat',
  //         })
  //       }
  //     })
  //   } else {
  //     that.mobileDecode(e.detail.iv, e.detail.encryptedData);//破解手机号码
  //   }
  //   let url = address + 'Interaction/chat';
  //   let params = { businessId: wx.getStorageSync('bId') };
  //   let sessionId = app.globalData.sessionId;
  //   util.nomeRequest(url, params,sessionId, function (res) {
  //     if (res == 1) {
  //       console.log('记录用户打开聊天成功！')
  //     }
  //   }, function () { });
  // },
  // // 破解手机号码
  // mobileDecode: function (iv, encryptedData) {
  //   let url = address + 'Tool/mobileDecode';
  //   let params = {
  //     openId: wx.getStorageSync('openId'),
  //     sessionKey: wx.getStorageSync('sessionKey'),
  //     encryptedData: encryptedData,
  //     iv: iv,
  //   };
  //   util.request(url, params, function (res) {
  //     app.globalData.phone = res;
  //     wx.setStorageSync('phone', res)
  //     wx.navigateTo({
  //       url: '../mall/subPackages/chat/chat',
  //     })
  //   }, function () { });

  // },
  // toChat: function () {
  //   wx.navigateTo({
  //     url: '../mall/subPackages/chat/chat',
  //   })
  // },
})